﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Ornament.MemberShip;
using Ornament.MemberShip.Permissions;
using Ornament.MVCWebFrame.Models;
using Ornament.Web.Mvc;
using Ornament.Web.Mvc.JQuery.FlexGrid;
using Ornament.MVCWebFrame.Models.MemberShips;

namespace Ornament.MVCWebFrame.Controllers
{

    #region

    #endregion

    /// <summary>
    /// </summary>   
    public class RoleController : Controller
    {
        // GET: /Role/

        /// <summary>
        /// </summary>
        /// <param name="pageIndex">
        /// The page index.
        /// </param>
        /// <returns>
        /// </returns>        
        public ActionResult Index()
        {
            ViewData["permissions"] = from p in MemberShipContext.CurrentContext.Factory.Permissions select p;
            return View();
        }

        /// <summary>
        /// </summary>
        /// <param name="roleName">
        /// The role name.
        /// </param>
        /// <returns>
        /// </returns>
        public ActionResult GetRole(string roleName)
        {
            var role = MemberShipContext.CurrentContext.Factory.Roles.Where(r => r.Name == roleName)
                .SingleOrDefault<Role>();
            var result = new
            {
                Name = role.Name,
                Comment = role.Comment,
                Permissions = (from p in role.Permissions select p.Id)
            };
            return Json(result);
        }

        /// <summary>
        /// </summary>
        /// <param name="subMitData">
        /// The sub mit data.
        /// </param>
        /// <returns>
        /// </returns>
        /// 
        public ActionResult GetRoles([ModelBinder(typeof(FlexGridSubmitDataBinder))] FlexGridSubmitData subMitData)
        {
            IRoleDao roleDao = MemberShipContext.CurrentContext.Factory.CreateRoleDao();
            int total;
            ReadOnlyCollection<Role> resultEntities = roleDao.GetRoles(subMitData.PageSize, subMitData.PageIndex,
                                                                       out total, subMitData.IsAsc, subMitData.SortName,
                                                                       subMitData.SearchType, subMitData.SearchValue);


            var result = new FlexGridResult { page = subMitData.PageIndex + 1, total = total };
            result.AddRows(resultEntities);
            return Json(result);
        }

        /// <summary>
        /// </summary>
        /// <param name="role">
        /// The role.
        /// </param>
        /// <returns>
        /// </returns>
        [JsonContainerFilter]
        public ActionResult Save(JsonContainer role)
        {
            Role roleEntity = MemberShipContext.CurrentContext.Factory.CreateRoleDao().Get(role.ToString("Name")) ??
                              new Role(role.ToString("Name"));

            roleEntity.Comment = role.ToString("Comment");
            roleEntity.Permissions.Clear();

            var permissionDao = MemberShipContext.CurrentContext.Factory.CreatePermissionDao();

            foreach (var id in role.ToArray<string>("permissions"))
            {
                roleEntity.Permissions.Add(permissionDao.Get(new Guid(id)));
            }

            return Json("保存成功");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public ActionResult Delete(string name)
        {
            string[] roleNames = name.Split(',');

            IRoleDao dao = MemberShipContext.CurrentContext.Factory.CreateRoleDao();
            string[] canBeDeletedRoles;

            IList<Role> cannotDeleteRole = dao.GetInUseRoles(roleNames, out canBeDeletedRoles);


            foreach (Role deleteRole in dao.GetRoles(canBeDeletedRoles))
            {
                if (deleteRole.Name == "admin")
                    continue;
                dao.Delete(deleteRole);
            }

            var sb = new StringBuilder();

            if (canBeDeletedRoles.Length != 0)
            {
                sb.Append("�ɹ�ɾ����ɫ" + String.Join(",", canBeDeletedRoles));
            }

            if (cannotDeleteRole.Count != 0)
            {
                var roles = from role in cannotDeleteRole select role.Name;
                sb.Append("��ɫ");
                sb.Append(String.Join(",", roles.ToArray()));
                sb.Append("���û�ʹ����,����޷�ɾ��");

            }
            if (cannotDeleteRole.Count == 0 && canBeDeletedRoles.Length == 0)
            {
                sb.Append("ɾ��ʧ��");
            }
            return Json(sb.ToString());
        }
    }
}